package com.cskaoyan.market.service.impl;

import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.db.domain.MarketAdminExample;
import com.cskaoyan.market.db.mapper.MarketAdminMapper;
import com.cskaoyan.market.service.AdminAdminService;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.MybatisUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 刘国兴
 * @description 管理员系统管理
 */
public class AdminAdminServiceImpl implements AdminAdminService {

    @Override
    public List<MarketAdmin> list(Map<String, String[]> parameterMap) {

        //利用MybatisUtil工具通过唯一的SqlSessionFactory获取Session
        //注意Session使用过后要及时关闭，确保不被共用
        SqlSession session = MybatisUtil.getSession();
        MarketAdminMapper mapper = session.getMapper(MarketAdminMapper.class);

        //创捷MarketAdmin的查询条件对象及其查询条件对象
        MarketAdminExample example = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = example.createCriteria();

        //处理一下参数,把原来参数value拼装为一整个字符串放到map，接下来使用map取参数
        Map<String, String> map = new HashMap<>();
        parameterMap.forEach((key, value) -> map.put(key, StringUtils.join(value)));

        //传递过来的参数page&limit&username&sort&order，页码&每页数量&用户名&排序字段&升降序
        if (StringUtils.isNotEmpty(map.get("username"))) {
            //用户名模糊查询
            criteria.andUsernameLike("%"+map.get("username")+"%");
        }

        //设置排序条件，记住" "的空格不要落下，不然格式有问题
        example.setOrderByClause(map.get("sort")+" "+map.get("order"));

        //设置分页,记得String转化位int
        PageHelper.startPage(Integer.parseInt(map.get("page")), Integer.parseInt(map.get("limit")));

        //执行查询
        List<MarketAdmin> adminList = mapper.selectByExample(example);
        session.commit();
        session.close();
        return adminList;
    }

    @Override
    public String create(String reqJson) throws JsonProcessingException {

        SqlSession session = MybatisUtil.getSession();
        MarketAdminMapper mapper = session.getMapper(MarketAdminMapper.class);

        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        MarketAdmin marketAdmin = objectMapper.readValue(reqJson, MarketAdmin.class);

        //新加三个参数
        marketAdmin.setAddTime(LocalDateTime.now());
        marketAdmin.setUpdateTime(LocalDateTime.now());
        marketAdmin.setDeleted(false);

        //验证一下参数，没问题就执行
        if (marketAdmin.getUsername() == null || marketAdmin.getPassword() == null || marketAdmin.getAvatar() == null || marketAdmin.getRoleIds() == null) {
            Object o = ResponseUtil.fail(401, "参数错误");
            session.close();
            return JacksonUtil.writeValueAsString(o);
        } else if (marketAdmin.getUsername().length() < 6 || marketAdmin.getPassword().length() < 6) {
            Object o = ResponseUtil.fail(402, "参数值错误");
            session.close();
            return JacksonUtil.writeValueAsString(o);
        } else {
            mapper.insertSelective(marketAdmin);
            session.commit();
            session.close();
            Object o = ResponseUtil.ok(marketAdmin);
            return JacksonUtil.writeValueAsString(o);
        }
    }

    @Override
    public String update(String reqJson) throws JsonProcessingException {
        SqlSession session = MybatisUtil.getSession();
        MarketAdminMapper mapper = session.getMapper(MarketAdminMapper.class);

        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        MarketAdmin marketAdmin = objectMapper.readValue(reqJson, MarketAdmin.class);

        marketAdmin.setUpdateTime(LocalDateTime.now());

        //验证一下参数，没问题就执行
        if (marketAdmin.getUsername() == null || marketAdmin.getPassword() == null || marketAdmin.getAvatar() == null || marketAdmin.getRoleIds() == null) {
            Object o = ResponseUtil.fail(401, "参数错误");
            session.close();
            return JacksonUtil.writeValueAsString(o);
        } else if (marketAdmin.getUsername().length() < 6 || marketAdmin.getPassword().length() < 6) {
            Object o = ResponseUtil.fail(402, "参数值错误");
            session.close();
            return JacksonUtil.writeValueAsString(o);
        } else {
            mapper.updateByPrimaryKeySelective(marketAdmin);
            session.commit();
            session.close();
            Object o = ResponseUtil.ok(marketAdmin);
            return JacksonUtil.writeValueAsString(o);
        }
    }

    @Override
    public String delete(String reqJson) throws JsonProcessingException {
        SqlSession session = MybatisUtil.getSession();
        MarketAdminMapper mapper = session.getMapper(MarketAdminMapper.class);
        Integer id = JacksonUtil.parseInteger(reqJson, "id");
        MarketAdmin marketAdmin = mapper.selectByPrimaryKey(id);

        if (marketAdmin != null) {
            mapper.deleteByPrimaryKey(id);
            session.commit();
            session.close();
            Object o = ResponseUtil.ok(marketAdmin);
            return JacksonUtil.writeValueAsString(o);
        } else {
            session.commit();
            session.close();
            Object o = ResponseUtil.fail(401, "参数错误");
            return JacksonUtil.writeValueAsString(o);
        }
    }
}
